package com.my.study.redisson.sub;

import com.my.study.redisson.constant.TaskConstants;
import com.my.study.redisson.model.ClientInfo;
import com.my.study.redisson.model.Message;
import com.my.study.redisson.timer.RedisClientTimer;
import com.my.study.redisson.timer.RedisServerTimer;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RMap;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * 客户端注册
 *
 * @author: yidujun
 * @create: 2021/11/08 16:20
 */
@Slf4j
@Component
public class SubscribeStartThread implements Callable<Integer> {

    @Resource
    RedissonClient redissonClient;

    private ClientInfo clientInfo;

    public void setClientInfo(ClientInfo clientInfo) {
        this.clientInfo = clientInfo;
    }

    @Override
    public Integer call() throws Exception {
        try {
            TimeUnit.MILLISECONDS.sleep(5500);

            // 向redis中注册当前服务信息（IP:PORT）
            RMap<String, Date> serverList = redissonClient.getMap(TaskConstants.SERVER_LIST);
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.SECOND, 40);
            serverList.put(clientInfo.toString(), calendar.getTime());

            // 通知其他服务
            RTopic topic = redissonClient.getTopic(TaskConstants.CHANNEL_SERVER_REST);
            log.info("[SubscribeStartThread] clientInfo = {}", clientInfo.toString());
            topic.publish(new Message("新增一个quartz实例...", clientInfo));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return -1;
        }
        return 1;
    }
}
